#!/bin/bash

# stagger main script
# Copyrights 2011 Sulaiman A. Mustafa <sigtermer@gmail.com>
# Distrobuted under the new BSD license

# Install loacation: Doesn't matter as long as the directory is in PATH

<< DEVELOPER_NOTES
	
	This script complements is the stagger bash script. a seperete script which
	handles changing directories can be found in misc/bash_completion.d/
	
	How it works
	read the developers notes in misc/bash_completion.d/stagger
	
	When the user invokes stagger from the cli, the following happens (I hope):
		
		1- Bash calls the function stagger() defined in the completion script.
		2- If the appropreate operation is defined in stagger(), it is executed.
		3- If not, this script is invoked with stagger() arguments passed to it.

End of
DEVELOPER_NOTES



function getfirststring {
	python -c "print '''$1'''.split()[0]"
}

function checkapp {
	$1 --version >& /dev/null > /dev/null
	if [[ "$?" != "0" ]]; then
		echo -e "Error: Could not run $1.\nInstall it and try again."
		exit 1
	fi
}

# requires a list of locations
function setuppath {
	x=`getfirststring $1`
	x="`stag -locate-database`$x"
	echo `dirname $x`
}



if [[ "$1" == "-goto" ]]; then
	#This should have been caught by bash's stagger() 
	echo "bash isn't configured poperly or goto might not be supported on your system."
	exit 1
fi

if [[ "$1" == "-goto-gui" ]]; then
	checkapp zenity
	checkapp python
	
	x=`zenity --entry --title="Open tag diectory.." --text="Enter as many tags relating to your target as posible. The first result will be selected."`
	if [[ "$x" == "" ]]; then
		zenity --error --title="Invalid input" --text="No tags were specified."
		exit 1
	fi
	
	x=`stag -find -- $x`
	if [[ "$x" == "" ]]; then
		zenity --error --text="No matches found!"
		exit 1
	fi	
	
	nautilus "`setuppath $x`"
fi

